// src/pages/Login/loginForm.js
import React,{useEffect, useState} from 'react';
import { Form, Input, Button,message } from 'antd';
import { useNavigate } from 'react-router-dom';
import http from '@/api/http';

const LoginForm = ({defaultUsername }) => {
  const [form] = Form.useForm();
  // 初始化表单值
  useEffect(()=>{
    if (defaultUsername) {
      form.setFieldsValue({ username: defaultUsername });
    }
  },[defaultUsername,form])
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const onFinish = async (values) => {
    try {
      const response = await http.post('/api/user/login', {
          username: values.username,
          password: values.password
      });
      if (response.code ===200) {
        // 存储token
        localStorage.setItem('token', response.data.token);
        message.success('登录成功');
        navigate('/dashboard')
        // const hrefUrl = 'http://123.57.67.13:8080/my/'
        // const redirectPath =`${hrefUrl}?token=${response.data.token}`
        // window.location.href = redirectPath
      } else {
        message.error(response.message || '登录失败');
      }
    } catch (error) {
      // 401 未授权处理
      if (error.response?.status === 401) {
        navigate('/login', { 
          replace: true,
          state: { from: location } 
        });
      }
    } finally {
      setLoading(false);
    }
  };
  return (
    <Form
      form={form}
      layout="vertical"
      onFinish={onFinish}
      requiredMark={false}
      className="login-form"
    >
      <Form.Item
        label="用户名"
        name="username"
        rules={[
          { required: true, message: '请输入用户名' },
          { max: 20, message: '用户名不能超过20个字符' }
        ]}
      >
        <Input placeholder="请输入用户名" allowClear />
      </Form.Item>

      <Form.Item
        label="密码"
        name="password"
        rules={[{ required: true, message: '请输入密码' }]}
        hasFeedback
      >
        <Input.Password placeholder="请输入密码" allowClear/>
      </Form.Item>
      <Button type="primary" block htmlType="submit">
        登录
      </Button>
    </Form>
  );
};

export default LoginForm;